package com.zj.common.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		response.setHeader("Access-Control-Allow-Origin", "*");  
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
        response.setHeader("Access-Control-Max-Age", "3600");  
        response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With,X-USERTOKEN,Content-Type, Accept");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String requestURI = request.getRequestURI();		
        if (requestURI.equals("/login.do") || requestURI.equals("/wxController.do") ||requestURI.equals("/downloadUtil.do")||requestURI.equals("/excelController.do")
        		||("/appletController.do").equals(requestURI)) {
			chain.doFilter(request, response);
		} else {
			//验证token
  			String token = request.getHeader("X-USERTOKEN");
			if(token == null){
				PrintWriter out = null;  
			    try {  
			        out = response.getWriter();
 			        String code = ResponseUtil.getJson(ResponseUtil.NOTOEKN_CODE, "用户未登录", "");
			        out.append(code);  
			       
			    } catch (IOException e) {  
			        e.printStackTrace();  
			    } finally {  
			        if (out != null) {  
			            out.close();  
			        }  
			    }  
				
			}
			else{		
					String id = TokenUtil.parseJWT(token);
					if(id.equals(ResponseUtil.TOKENFALSE_CODE)){
						PrintWriter out = null;  
					    try {  
					        out = response.getWriter();
					        String code = ResponseUtil.getJson(ResponseUtil.TOKENFALSE_CODE, "用户未登录", "");
					        out.append(code);  
					        
					    } catch (IOException e) {  
					        e.printStackTrace();  
					    } finally {  
					        if (out != null) {  
					            out.close();  
					        }  
					    }  
					}else{
					request.setAttribute("id", id);
					chain.doFilter(request, response);
					}
				
			}
		}
			
//			//测试通过
//			
//			request.setAttribute("id", "312");
//			chain.doFilter(request, response);

		
	}

	public void init(FilterConfig config) throws ServletException {

	}

}